package cn.sourcespro.spring.controller;

import cn.sourcespro.spring.crudparams.dto.AddUserDto;
import cn.sourcespro.spring.entity.User;
import cn.sourcespro.spring.service.UserService;
import cn.sourcespro.spring.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * security
 *
 * @author zhanghaowei
 * @date 2018/7/25
 */
@Controller
public class HomeController {


    @Autowired
    private UserService userService;
    @Autowired
    private PasswordEncoder passwordEncoder;


    @RequestMapping("/")
    public String index(Model model) {
        model.addAttribute("msg", "只对管理员显示");
        return "index";
    }

    @GetMapping("login")
    String login() {
        return "login";
    }
    @GetMapping("reg")
    String reg(){
        return "reg";
    }

    @PostMapping("reg")
    @ResponseBody
    String reg(AddUserDto dto){
        User user = new User();
        user.setUsername(dto.getUsername());
        user.setNickname(dto.getNickname());
        String encode = passwordEncoder.encode(dto.getPassword());
        user.setPassword(encode);

        userService.add(user);
        return "ok";
    }

    @PreAuthorize("hasAuthority('USER')")
    @RequestMapping(value="/admin/test1")
    @ResponseBody
    public String adminTest1() {
        return "ROLE_USER";
    }

    @PreAuthorize("hasAuthority('ADMIN')")
    @RequestMapping("/admin/test2")
    @ResponseBody
    public String adminTest2() {
        return "ROLE_ADMIN";
    }

}
